﻿using Microsoft.AspNetCore.Http;
using System.Net;

namespace MelodysDemo.Application.AppServices
{
    public static class ToGetIP
    {
        public static string GetUserIP()
        {
            //获取当前计算机的主机名。主机名是在计算机上唯一标识它的名称
            string hostName = Dns.GetHostName();
            //使用主机名获取与该主机名相关联的所有 IP 地址。返回的是一个 IPAddress 数组
            IPAddress[] addresses = Dns.GetHostAddresses(hostName);
            foreach (IPAddress address in addresses)
            {
                //检查当前遍历的 IP 地址是否为 IPv4 地址 (InterNetworkV6 表示IPV6)
                if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) // IPv4
                {
                    //返回当前连接的网络的IPV4地址
                    return address.ToString();
                }
                else if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)//IPV6
                {
                    //返回当前连接的网络的IPV6地址
                    return address.ToString();
                }
            }
            return null;
        }
    }
}
